package com.tea.servlet;

import com.tea.service.ReviewService;
import com.tea.service.impl.ReviewServiceImpl;
import com.tea.entity.Review;
import com.tea.entity.User;
import com.tea.util.URLUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@WebServlet("/comment")
public class CommentServlet extends HttpServlet {
    private ReviewService reviewService = new ReviewServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            String redirectUrl = URLUtil.buildRedirectUrl("/login.jsp", "message", "请先登录后再评论");
            response.sendRedirect(redirectUrl);
            return;
        }

        long productId = 0;
        try {
            productId = Long.parseLong(request.getParameter("productId"));
            String content = request.getParameter("content");
            String ratingStr = request.getParameter("rating");

            if (content == null || content.trim().isEmpty()) {
                String redirectUrl = URLUtil.buildErrorRedirectUrl("/product-detail?productId=" + productId, "评论内容不能为空");
                response.sendRedirect(redirectUrl);
                return;
            }

            if (ratingStr == null || ratingStr.trim().isEmpty()) {
                String redirectUrl = URLUtil.buildErrorRedirectUrl("/product-detail?productId=" + productId, "请选择评分");
                response.sendRedirect(redirectUrl);
                return;
            }

            // 检查用户是否已经对该商品发表过评论
            if (reviewService.hasUserReviewedProduct(user.getId(), productId)) {
                String redirectUrl = URLUtil.buildErrorRedirectUrl("/product-detail?productId=" + productId, "您已经对该商品发表过评论了");
                response.sendRedirect(redirectUrl);
                return;
            }

            Review review = new Review();
            review.setProductId(productId);
            review.setUserId(user.getId());
            review.setUsername(user.getUsername());
            review.setContent(content.trim());
            review.setRating(Integer.parseInt(ratingStr));
            review.setCreateTime(new Date());
            // 设置订单ID为0，表示非订单评论（将在DAO层转换为NULL）
            review.setOrderId(0);

            int result = reviewService.addReview(review);
            if (result > 0) {
                // 成功添加评论，重定向到商品详情页并显示成功消息
                String redirectUrl = URLUtil.buildSuccessRedirectUrl("/product-detail?productId=" + productId, "评论提交成功");
                response.sendRedirect(redirectUrl);
            } else {
                String redirectUrl = URLUtil.buildErrorRedirectUrl("/product-detail?productId=" + productId, "评论提交失败，请重试");
                response.sendRedirect(redirectUrl);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            String redirectUrl = URLUtil.buildErrorRedirectUrl("/product-detail?productId=" + productId, "评分格式错误");
            response.sendRedirect(redirectUrl);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Comment submission error: " + e.getMessage());
            String redirectUrl = URLUtil.buildErrorRedirectUrl("/product-detail?productId=" + productId, "评论提交失败：" + e.getMessage());
            response.sendRedirect(redirectUrl);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            long productId = Long.parseLong(request.getParameter("productId"));
            List<Review> reviews = reviewService.getReviewsByProductId(productId);
            request.setAttribute("comments", reviews);
            request.getRequestDispatcher("/product-detail.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "获取评论失败");
            request.getRequestDispatcher("/product-detail.jsp").forward(request, response);
        }
    }
}